<?php
date_default_timezone_set('PRC'); 
/**
 * 考勤审批流程
 * @copyright (c) 2018, gandianli
 */
class service_appprocess extends gdl_components_baseservice
{
	# 默认留底照片
	static public $photo = "";
	
	#需要用到的model
	public $groupModel;#考勤组
	public $processModel;#审批流程规则表
	public $groupUserModel; #人员所属考勤组
	public $pecialPeopleModel;#特殊流程人员表
	public $userModel;#人员表
	public $unitModel; #组织架构表
	public $approvalModel; #审批层级表 
	public $outGoModel; #外出申请记录表
	public $cardModel; #补卡申请记录表
	public $leaveModel; #请假申请记录表
	public $msgModel; #消息中心记录表
	public $attRecordModel; #考勤记录表
	
    public function __construct()
    {
        parent::__construct();
		$this->groupModel = new model_attendance_attendancegroup(); 
		$this->processModel = new model_attendance_approvalprocess(); 
		$this->groupUserModel = new model_attendance_attendancegroupuser();
		$this->pecialPeopleModel = new model_attendance_approvalprocessspecialpeople(); 
		$this->userModel = new model_attendance_member(); 
		$this->unitModel = new model_lhbase_units();
		$this->approvalModel = new model_attendance_approvalrecord();
		$this->outGoModel = new model_attendance_appoutgorecord();
		$this->cardModel = new model_attendance_approvalprocesscardreplacementrecord();
		$this->leaveModel = new model_attendance_approvalprocessleaverecord();
		$this->msgModel = new model_attendance_messagerecord();
		$this->attRecordModel = new model_attendance_attendancerecord();
    }

    /**
     * 读取该用户的审批流程 用于获取该用户的审批流程规则 插入申请记录表里
     * @param $userId 用户id
	 * @param $platformId 平台id
	 * @param $type  1：请假审批流程 2：外出审批流程 3：补卡审批流程  如还需要添加其他流程请新增字段
     * @return array
     */
    public function getMemberProcess($userId, $platformId, $type=1)
    {
		#逻辑：先查询该用户是否属于特殊人员如果属于直接获取审批流程ID  不属于则再查询他属于那个考勤组 通过考勤组的外出审批流程ID获取审批流程
		# 查询审批流程规则 是否在特殊人员流程里
		$pecialWhere = "memberId={$userId}"; #是否要加平台id
		$pecialId = $this->pecialPeopleModel->selectOne($pecialWhere, "id,approvalProcessId,memberId");
		
		# 如果不属于特殊人群则去找考勤组里默认的外出审批流程
		if(!empty($pecialId['approvalProcessId'])){
			$proId = $pecialId['approvalProcessId']?$pecialId['approvalProcessId']:""; #考勤id
		}else{
			
			#查到人员所属考勤组 如果没有考勤组则查找该平台下的默认审批流程
			$memberWhere = "memberId={$userId} and platformId={$platformId} "; #  and status=0 #目前做的物理删除该字段暂未用到 type1:参与考勤人员 2：无需参与考勤人员 #type=1 and
			$memberGroup = $this->groupUserModel->selectOne($memberWhere, 'agId');
			$agId = $memberGroup['agId'] ? $memberGroup['agId'] : 0; #考勤组id
			
			#继续去找考勤组的 外出 请假 补卡审批流程ID
			$groupProcessWhere = "id={$agId} and isDelete=0 and platformId={$platformId}";
			$groupProcess = $this->groupModel->selectOne($groupProcessWhere, 'id,approvalProcessOne,approvalProcessTwo,approvalProcessThree');
			if($type==1){ # 请假
				$proId = $groupProcess['approvalProcessOne'] ? $groupProcess['approvalProcessOne'] : "";
			}
			if($type==2){ # 外出
				$proId = $groupProcess['approvalProcessTwo'] ? $groupProcess['approvalProcessTwo'] : ""; 
			}
			if($type==3){ #补卡
				$proId = $groupProcess['approvalProcessThree'] ? $groupProcess['approvalProcessThree'] : "";
			}
		}
		
		# 获取审批流程ID proId
		if(!empty($proId)){ #如果不为空就走正常流程
			$processWhere = "id={$proId} and platformId={$platformId} and stop=1";
			$processInfo = $this->processModel->selectOne($processWhere, 'id,name,rules,status,type');
		}
		
		#如果找不到审批流程就找最终的默认审批流程
		if(empty($proId) || empty($processInfo))
		{ #如果为空则取该平台下的默认审批流程
			$processWhere = "platformId={$platformId} and stop=1 and status=1 ";
			# 选择性开启，如果一个平台有多个默认流程就开启 如果只有一个默认审批流程注释
			if($type==1){ #请假
				$processWhere.=" and type=1";
			}
			if($type==2){ #外出
				$processWhere.="and type=2";
			}
			if($type==3){ #补卡
				$processWhere.="and type=3";
			}
			$processInfo = $this->processModel->selectOne($processWhere, 'id,name,rules,status,type');
		}
		return $processInfo?$processInfo:[];
    }
	
	/**
     * 重组审批流程 用于用户申请请假 补卡 外出时的审批流程图 【申请页面视角】
	 * 规则：[1]=>
	 *		array(3) {
	 *		["level"]=>
	 *		string(1) "1"
	 *		["type"]=>
	 *		string(17) "target_management"
	 *		["name"]=>
	 *		string(12) "一级主管"
	 *		}
	 *		[2]=>
	 *		array(3) {
	 *		["type"]=>
	 *		string(13) "target_member"
	 *		["name"]=>
	 *		string(9) "王大权"
	 *		["target_member"]=>
	 *		string(8) "manager6"
	 *		}
     * @param $userId 用户id
	 * @param $rules 考勤规则，为一个序列化数组[注意 传入的规则必须为一个序列化数组]
     * @return array
     */ 
	 public function actionApprocess($userId, $rules){
		 $resultRule = [];
		 #用户id 和 序列化数组必传
		 if(empty($userId))return false;
		 if(empty($rules))return false;
		 
		 # 主管：target_management leve 人员：target_member approvals：manager3 
		 #查询用户的平台id和unitsid
		 $userInfoWhere = "id={$userId} and status=2";
		 $userInfo = $this->userModel->selectOne($userInfoWhere, 'id,platformId,unitId,isCharge,photo,realName');
		 if(empty($userInfo))return false;
		 $platformId = $userInfo['platformId'] ? $userInfo['platformId']:0;
		 $unitId = $userInfo['unitId'] ? $userInfo['unitId']:0;
		 $myPid = $unitId?$unitId:0;
		 
		 #如果是部门主管再去找他的上级主管
		 if($userInfo['isCharge']==1){
			 $chargeUnitsWhere =  "isDelete=1 and id={$unitId} and platformId={$platformId}";
			 $chargeUnits = $this->unitModel->selectOne($chargeUnitsWhere, 'id,parentId');
			 $unitId = $chargeUnits['parentId'] ? $chargeUnits['parentId'] : $unitId;
			 
		 }
		 
		 #遍历审批流程
		 $unRules = unserialize($rules);
		 #断点规则根据此规则拆分 
		 $j = 1; #第几级主管
		 for($i=0; $i<count($unRules); $i++){
			 # 找主管
			 if($unRules[$i]['type']=='target_management'){ 
				if($userInfo['isCharge']==1){ #如果是部门主管则找上级，不是则找自己的 2018-8-17 之前没有myPid
					$leaderUser = $this->getLeader($myPid,$platformId,$unRules[$i]['level']); #通过层级找 可能是一二三或二三四级
				}else{
					$leaderUser = $this->getLeader($unitId,$platformId,$unRules[$i]['level']-1); #通过层级找 可能是一二三或二三四级
				} 
				$resultRule[$j]['user'] = $leaderUser?$leaderUser:[];
				$resultRule[$j]['level'] = $j;
				$resultRule[$j]['levelName'] = $unRules[$i]['name']?$unRules[$i]['name']:"审批人";
			 }
			 #找直接人员
			 if($unRules[$i]['type']=='target_member'){
				$myUserId = @str_replace('manager','',$unRules[$i]['target_member']); 
				$myUserWhere = "id={$myUserId}";
				$myUserInfo = $this->userModel->selectOne($myUserWhere,'id,realName,unitId,platformId,isCharge,photo');
				$myUnitId = $myUserInfo['unitId'] ? $myUserInfo['unitId'] : 0;
				$myPhoto = $myUserInfo['photo'] ? $myUserInfo['photo']:"";
				if(empty($myUserInfo['photo'])){$myPhoto=self::$photo;}
				$resultRule[$j]['user'][] = ['id'=>$myUserInfo['id'],'realName'=>$myUserInfo['realName'],'photo'=>$myPhoto];
				$resultRule[$j]['level'] = $j;
				$resultRule[$j]['levelName'] = "审批人";
			 }
			 
			 $j++;
		 }
		 #遍历去空 去重
		 $endResult = $this->getEndApprovalList($resultRule);
		 #如果自己是主管，未发现审批人，那就自己审核自己
		 if(empty($endResult)){
			 if($userInfo['isCharge']==1){
				$myPhoto = $userInfo['photo']?$userInfo['photo']:self::$photo;
				$endResult[1]['user'][] = ['id'=>$userInfo['id'],'realName'=>$userInfo['realName'],'photo'=>$myPhoto];
				$endResult[1]['level'] = 1;
				$endResult[1]['levelName'] = "审批人";
			 }
		 }
		 return $endResult?$endResult:[];
	 }
	 //找上级 
	 private function getLeader($unitId, $platformId, $level=0){
		$userList = [];
		$unitId = $unitId ? $unitId : $unitId; 
		$level = intval($level);
		#找上级
		$pid = $unitId;
		if($level!=0){
			for($i=0; $i<$level; $i++){
				$where = "isDelete=1 and id={$pid}";
				$filed = "id,parentId";
				$parentInfo = $this->unitModel->selectOne($where, $filed);
				$pid = !empty($parentInfo['parentId'])?$parentInfo['parentId']:$unitId; 
			}
			#如果pid等于单位id那说明他没有最高级 需要去除这个级别直接跳过三级向二级审批 8-11日
			if($pid==$unitId){return $userList;}
		}

		#如果有则继续查询该平台下的用户
		$leaderWhere = "unitId={$pid} and status=2 and isCharge=1 and platformId={$platformId}";
		$filed = "id,realName,photo";
		$userList = $this->userModel->select($leaderWhere, $filed)->items;
		if(!empty($userList)){
		 for($i=0; $i<count($userList); $i++){
			 if(empty($userList[$i]['photo'])){
				$userList[$i]['photo'] = self::$photo;
			 }
		 }
		} 
		return $userList?$userList:[];
	 }
	// 去重去空审批流程 带审核意见的 完整的
	// 此函数可用于去除重复审批人操作【暂未实现】
	private function getEndApprovalList($list=[]){
		#最终返回
		$newList = [];
		$j=1;
		$jLeng = count($list);
		$inStrArray = [];
		$emptyUserId = [];
		for($i=1; $i<=$jLeng; $i++){
			if(!empty($list[$i]['user'])){
				$newList[$j]['user'] = $list[$i]['user'];
				$newList[$j]['level'] = $j;
				$newList[$j]['levelName']= $list[$i]['levelName'];
				
				#去重核心
				$userLeng = count($list[$i]['user']);
				if($userLeng==1){
					#记录id和层级
					for($y=0; $y<$userLeng; $y++){
						#如果相等则记录重复的id
						if(in_array($list[$i]['user'][$y]['id'],$emptyUserId)){
							$inStrArray[] = ['level'=>$j,'userId'=>$list[$i]['user'][$y]['id']];
						}
						$emptyUserId[] = $list[$i]['user'][$y]['id'];
					}
				}#去重核心
				
				$j++;
			}
		}
		
		#如果不为空说明有重复的值
		if(!empty($inStrArray)){		
			$emptyInArray = [];
			for($z=0; $z<count($inStrArray); $z++){
				$emptyInArray[] = $inStrArray[$z]['level'];
			}
			#去除重复用户
			$emptyArray = [];
			$k = 1;
			$kLeng = count($newList);
			for($x=1; $x<=$kLeng; $x++){
				if(!in_array($newList[$x]['level'],$emptyInArray)){
					$emptyArray[$k]['user'] = $newList[$x]['user'];
					$emptyArray[$k]['level'] = $k;
					$emptyArray[$k]['levelName'] = $newList[$x]['levelName'];
					$k++;
				}
			}
			if(!empty($emptyArray)){
				return $emptyArray;
			}
		}
		
		return $newList ? $newList : [];
	}
	/**
     * 插入审批流程状态 用户提交申请后调用此方法向审批流程表里插入数据
     * @param $userId 用户id
	 * @param $rules 考勤规则，为一个序列化数组
	 * @param $recordId 添加外勤 请假  补卡记录id
	 * @param $type  1：请假审批流程 2：外出审批流程 3：补卡审批流程  如还需要添加其他流程请新增字段
     * @return array
     */
	public function insertApproval($userId, $rule, $recordId, $type){
		if(empty($userId))return false;
		if(empty($rule))return false;
		if(empty($recordId))return false; 
		
		#获取审批
		$myRule = $this->actionApprocess($userId, $rule);
		#最大层
		$maxLevel = 0;
		for($i=1; $i<=count($myRule); $i++){
			for($k=0; $k<count($myRule[$i]['user']); $k++){
				$insertData = [
					'coverMemberId'=>$userId,
					'memberId'=>$myRule[$i]['user'][$k]['id'],
					'memberPid'=>isset($myRule[$i+1]['user'][$k]['id']) ? $myRule[$i+1]['user'][$k]['id'] : 0,
					'adopt'=>1,
					'recordId'=>$recordId,
					'type'=>$type,
					'level'=>$myRule[$i]['level'],
					'levelName'=>$myRule[$i]['levelName'],
					'maxLevel'=>2, #1:最后一级 2：不是
					'isShow'=>2,#1：可见 2：不可见 
					'createTime'=>time(),
				]; 
				$ret = $this->approvalModel->insert($insertData);
			}
			$maxLevel = $myRule[$i]['level'];
		}
		//var_dump($maxLevel);exit;
		#修改第一级为可见 可见才能查看到审批 不可见即第n级看不到申请
		$upWhere = "coverMemberId={$userId} and recordId={$recordId} and level=1";
		$upData = ['isShow'=>1];
		$this->approvalModel->update($upWhere, $upData);
		
		#申请成功立即提交msg插入一条消息 审批人
		#找到审批人id和
		$approvalWhere  = "coverMemberId = {$userId} and recordId={$recordId} and level=1";
		$approvalInfo = $this->approvalModel->select($approvalWhere, 'id,memberId')->items;
		foreach($approvalInfo as $v){
			$this->insertMessage(['type'=>2,'recordId'=>$recordId,'approvalId'=>$v['id'],'userId'=>$v['memberId'],'msgInfo'=>'我审批的','createTime'=>time()]);
		}
		#被审批人插入一条消息
		$this->insertMessage(['type'=>2,'recordId'=>$recordId,'approvalId'=>$approvalInfo[0]['id']?$approvalInfo[0]['id']:"0",'userId'=>$userId,'msgInfo'=>'我的申请','createTime'=>time()]);
		
		#找到最后一级并标记
		$levelWhere = "coverMemberId={$userId} and recordId={$recordId} and level={$maxLevel} and type={$type}";
		$levelData = ['maxLevel'=>1];
		$this->approvalModel->update($levelWhere, $levelData);
		
		return $ret?$ret:false; 
	}
	/**
     * 获取审批流程状态 我的申请状态 第一视角 用户成功提交申请后查看的审批进度
     * @param $userId 用户id
	 * @param $rules 考勤规则，为一个序列化数组
	 * @param $recordId 添加外勤 请假 补卡  的id
	 * @param $type  1：请假审批流程 2：外出审批流程 3：补卡审批流程  如还需要添加其他流程请新增字段
     * @return array
     */
	 public function approvalStatus($userId, $recordId, $type){
		#查出审批流程
		$where = "coverMemberId={$userId} and recordId={$recordId} and type={$type}";
		$list = $this->approvalModel->select($where, 'id,coverMemberId,memberId,memberPid,adopt,isShow,info,updateTime as bb,recordId,level,FROM_UNIXTIME(updateTime, "%Y.%m.%d %H:%i") as updateTime,createTime,levelName','ORDER BY level ASC')->items;
		#遍历获取每层审批者的信息
		for($k=0; $k<count($list); $k++){
			$userWhere = "id={$list[$k]['memberId']}";
			$userInfo = $this->userModel->selectOne($userWhere, 'id,realName,photo');
			$list[$k]['photo'] = $userInfo['photo'] ? $userInfo['photo']:self::$photo;
			$list[$k]['realName'] = $userInfo['realName']?$userInfo['realName']:"";
			if(empty($list[$k]['info'])){
				$list[$k]['info'] = "";
			}
		};
		#获取用户的信息
		$myWhere = "id={$userId}";
		$myUserInfo = $this->userModel->selectOne($myWhere, 'id,realName,photo');
		#补全字段
		$myUserInfo['adopt'] = "0";
		$myUserInfo['coverMemberId'] = "0";
		$myUserInfo['id'] = "0";
		$myUserInfo['info'] = "0";
		$myUserInfo['level'] = "0";
		$myUserInfo['memberId'] = "0";
		$myUserInfo['memberPid'] = "0";
		$myUserInfo['recordId'] = "0";
		$myUserInfo['updateTime'] = date("Y-m-d H:i", $list[0]['createTime']);
		$myUserInfo['createTime'] =$list[0]['createTime'];
		$myUserInfo['waitTime'] =0;
		$myUserInfo['isShow'] =1;
		$myUserInfo['bb'] =0;
		#遍历获取每个层级的状态
		$newList = [];
		$newList[0]['user'][0] = $myUserInfo;
		$newList[0]['level'] = 0;
		$newList[0]['levelName'] = "发起人";
		for($i=0; $i<count($list); $i++){
			$list[$i]['waitTime'] = "";
			if(empty($list[$i]['waitTime'])){
				if($list[$i]['adopt']!=1){
					$list[$i]['waitTime'] = $list[$i]['updateTime']?$list[$i]['updateTime']:$list[$i]['createTime'];
				}else{
					if(empty($list[$i]['waitTime'])){
						$list[$i]['waitTime'] = $this->getFormatDate($list[$i]['createTime']);
					}
				}
			}
			$newList[$list[$i]['level']]['user'][] =$list[$i];
			$newList[$list[$i]['level']]['level']= $list[$i]['level'];
			$newList[$list[$i]['level']]['levelName']= $list[$i]['levelName'];
		}
		#多层遍历取最终
		$endRet = [];
		for($i=0; $i<count($newList); $i++){
			$endRet[$i]['level'] = $newList[$i]['level'];
			$endRet[$i]['levelName'] = $newList[$i]['levelName'];
			$dropt = 0; # 未通过
			$name = [];#姓名拼接
			$photo = ""; #头像
			$info = "";
			$updateTime = "";
			$isShow = 2; #1可见 2不可见
			$bb = "";
			for($k=0;$k<count($newList[$i]['user']);$k++){
				if($newList[$i]['user'][$k]['adopt']!=1){ #通过了
					$dropt = $newList[$i]['user'][$k]['adopt'];
					$name[] = $newList[$i]['user'][$k]['realName'];
					$photo = $newList[$i]['user'][$k]['photo']?$newList[$i]['user'][$k]['photo']:"";
					$updateTime = $newList[$i]['user'][$k]['updateTime'];
					if(empty($info)){
						$info = $newList[$i]['user'][$k]['info']?$newList[$i]['user'][$k]['info']:"";
					}
					$forShow = $newList[$i]['user'][$k]['isShow'];
					$isShow =$forShow;
				}else{
					$photo = $newList[$i]['user'][$k]['photo']?$newList[$i]['user'][$k]['photo']:"";
					$name[]=$newList[$i]['user'][$k]['realName'];
					if($dropt==0){
						$dropt = $newList[$i]['user'][$k]['adopt'];
					}
					$updateTime = $newList[$i]['user'][$k]['waitTime'];
					if(empty($info)){
						$info = $newList[$i]['user'][$k]['info']?$newList[$i]['user'][$k]['info']:"";
					}
					if($dropt==2 || $dropt==3 || $dropt==4){
						
					}else{
						$isShow =$newList[$i]['user'][$k]['isShow'];
					}
				}
				#计算时间
				if(empty($bb)){
					$bb = $newList[$i]['user'][$k]['bb'];
				}
			}
			$endRet[$i]['userInfo'] = ['adopt'=>$dropt,'userName'=>$name,'photo'=>$photo,'createTime'=>$updateTime,'info'=>$info,'isShow'=>$isShow,'bb'=>$bb];
		} 
		$endRet[0]['userInfo']['createTime'] = date("Y-m-d H:i", $list[0]['createTime']);
		
		#最后一次遍历修改时间
		for($j=0; $j<count($endRet); $j++){
			if($j>0){
				if($endRet[$j]['userInfo']['adopt']!=1){
					$endRet[$j]['userInfo']['createTime'] = date("Y-m-d H:i", $endRet[$j]['userInfo']['bb']);
				}
			}
		}
		
		return $endRet;
	 }
	 /**
	 * 第三方视角 审批流程申请状态 第三方用户 非本人查看审批流程进度展示
	 * @param $recordId 添加外勤 请假 补卡 的id
	 * @param $type  1：请假审批流程 2：外出审批流程 3：补卡审批流程  如还需要添加其他流程请新增字段
	 */
	 public function showApprovalStatus($recordId, $type){ 
		$where = "recordId={$recordId} and type={$type}";
		$list = $this->approvalModel->select($where, 'id,coverMemberId,memberId,memberPid,adopt,info,isShow,recordId,level,updateTime as bb,FROM_UNIXTIME(updateTime, "%Y.%m.%d %H:%i") as updateTime,createTime,levelName','ORDER BY level ASC')->items;
		
		#遍历获取每层审批者的信息
		for($k=0; $k<count($list); $k++){
			$userWhere = "id={$list[$k]['memberId']}";
			$userInfo = $this->userModel->selectOne($userWhere, 'id,realName,photo');
			$list[$k]['photo'] = $userInfo['photo'] ? $userInfo['photo']:self::$photo;
			$list[$k]['realName'] = $userInfo['realName']?$userInfo['realName']:"";
		}
		
		$userId = $list[0]['coverMemberId'] ? $list[0]['coverMemberId'] : 0;
		
		#获取用户的信息
		$myWhere = "id={$userId}";
		$myUserInfo = $this->userModel->selectOne($myWhere, 'id,realName,photo');
		#补全字段
		$myUserInfo['adopt'] = "0";
		$myUserInfo['coverMemberId'] = "0";
		$myUserInfo['id'] = "0";
		$myUserInfo['info'] = "0";
		$myUserInfo['level'] = "0";
		$myUserInfo['memberId'] = "0";
		$myUserInfo['memberPid'] = "0";
		$myUserInfo['recordId'] = "0";
		$myUserInfo['updateTime'] = date("Y-m-d H:i", $list[0]['createTime']);
		$myUserInfo['createTime'] =$list[0]['createTime'];
		$myUserInfo['waitTime'] =0;
		$myUserInfo['isShow'] = 1;
		$myUserInfo['bb'] = date("Y-m-d H:i", $list[0]['createTime']);
		
		#遍历获取每个层级的状态
		$newList = [];
		$newList[0]['user'][0] = $myUserInfo;
		$newList[0]['level'] = 0;
		$newList[0]['levelName'] = "发起人";
		for($i=0; $i<count($list); $i++){
			$list[$i]['waitTime'] = "";
			if(empty($list[$i]['waitTime'])){
				if($list[$i]['adopt']!=1){
					$list[$i]['waitTime'] = $list[$i]['updateTime']?$list[$i]['updateTime']:$list[$i]['createTime'];
				}else{
					if(empty($list[$i]['waitTime'])){
						$list[$i]['waitTime'] = $this->getFormatDate($list[$i]['createTime']);
					}
				}
			}
			$newList[$list[$i]['level']]['user'][] =$list[$i];
			$newList[$list[$i]['level']]['level']= $list[$i]['level'];
			$newList[$list[$i]['level']]['levelName']= $list[$i]['levelName'];
		}
		
		#多层遍历取最终
		$endRet = [];
		for($i=0; $i<count($newList); $i++){
			$endRet[$i]['level'] = $newList[$i]['level'];
			$endRet[$i]['levelName'] = $newList[$i]['levelName'];
			$dropt = 0; # 未通过
			$name = [];#姓名拼接
			$photo = ""; #头像
			$updateTime = "";
			$info = "";
			$isShow = 2;
			$bb = "";
			for($k=0;$k<count($newList[$i]['user']);$k++){
				$forShow = 0;
				if($newList[$i]['user'][$k]['adopt']!=1){ #通过了
					$dropt = $newList[$i]['user'][$k]['adopt'];
					$name[] = $newList[$i]['user'][$k]['realName'];
					$photo = $newList[$i]['user'][$k]['photo']?$newList[$i]['user'][$k]['photo']:"";
					$updateTime = $newList[$i]['user'][$k]['updateTime'];
					if(empty($info)){
						$info = $newList[$i]['user'][$k]['info']?$newList[$i]['user'][$k]['info']:"";
					}
					$forShow = $newList[$i]['user'][$k]['isShow'];
					$isShow =$forShow;
				}else{
					$photo = $newList[$i]['user'][$k]['photo']?$newList[$i]['user'][$k]['photo']:"";
					$name[]=$newList[$i]['user'][$k]['realName'];
					if($dropt==0){
						$dropt = $newList[$i]['user'][$k]['adopt'];
					}
					$updateTime = $newList[$i]['user'][$k]['waitTime'];
					if(empty($info)){
						$info = $newList[$i]['user'][$k]['info']?$newList[$i]['user'][$k]['info']:"";
					}
					if($dropt==2 || $dropt==3 || $dropt==4){
						
					}else{
						$isShow =$newList[$i]['user'][$k]['isShow'];
					}
				}
				#计算时间
				if(empty($bb)){
					$bb = $newList[$i]['user'][$k]['bb'];
				}
				
			}
			$endRet[$i]['userInfo'] = ['adopt'=>$dropt,'userName'=>$name,'photo'=>$photo,'createTime'=>$updateTime,'info'=>$info,'isShow'=>$isShow,'bb'=>$bb];
		} 
		$endRet[0]['userInfo']['createTime'] = date("Y-m-d H:i", $list[0]['createTime']);
		
		#最后一次遍历修改时间
		for($j=0; $j<count($endRet); $j++){
			if($j>0){
				if($endRet[$j]['userInfo']['adopt']!=1){
					$endRet[$j]['userInfo']['createTime'] = date("Y-m-d H:i", $endRet[$j]['userInfo']['bb']);
				}
			}
		}
		return $endRet;
	 }
	 
	 /**
	 *	#拒绝则推送消息给被审批用户 type：请假 recordId：approvalRecordId:请假记录id msg：审批消息
	 *	$extrasOne = ['extras'=>['type'=>1,'recordId'=>$recordId,'approvalRecordId'=>$id,'msg'=>'请假已被驳回']];
	 *	$aliasOne = [$coverMemberId];
	 *	$msgOne = "你的请假已被驳回";
	 *	$this->jpush->jpushOneMessage($msgOne,$aliasOne, $extrasOne);  # 推送到指定用户 
	 * 主管审批用户申请 
	 * @param $id atd_approve_record里的id 申请记录表里的id 
	 * @param $status 审批状态1：拒绝 2：通过
	 * @param $info 审核意见
	 * @param $type  1：请假审批流程 2：外出审批流程 3：补卡审批流程  如还需要添加其他流程请新增字段
	 */
	 public function editApproval($id,$status=1,$info="未填写审核", $type){ 
		#根据层级id直接获取 被审批人id 和审批人id 还有申请记录id
		//$approvalWhere = "coverMemberId={$coverMemberId} and memberId={$memberId} and type={$type} and recordId={$recordId}";
		#需要审批的用户
		$approvalWhere = "id={$id}";
		$approvalInfo = $this->approvalModel->selectOne($approvalWhere, '*');
		
		#各项id
		$memberId = $approvalInfo['memberId']?intval($approvalInfo['memberId']):""; #审批人id
		$coverMemberId = $approvalInfo['coverMemberId']?intval($approvalInfo['coverMemberId']):""; #被审批人id
		$recordId = $approvalInfo['recordId']?intval($approvalInfo['recordId']):""; #申请记录id
		$level = $approvalInfo['level']?intval($approvalInfo['level']):""; #层级
		$maxLevel = $approvalInfo['maxLevel']?$approvalInfo['maxLevel']:2;  #1：最后一级 2：不是最后一级
		#做限制 当同级的有第一个人审核通过了则不再审核
		$endWhere = "level={$level} and recordId={$recordId} and type={$type} and coverMemberId={$coverMemberId} and (adopt=2 or adopt =3 or adopt=4)";
		$endEmpty = $this->approvalModel->selectOne($endWhere, "id");
		if($endEmpty){
			return false;
		}
		
		$upApprovalWhere = "id={$id}";
		#修改审批层级表的状态
		if($status==1){ #jujue
			$adopt = 3;
			#改他为可见并且其他不可见
			$recordWheres = "id<>{$id} and level>={$level}  and coverMemberId={$coverMemberId} and recordId={$recordId}";
			$upRecordId = ['isShow'=>2]; #其他同级或者其他为不可见
			$this->approvalModel->update($recordWheres, $upRecordId);
		}
		if($status==2){ #tongguo
			$adopt = 2;
			#改他为可见并且其他不可见
			$recordWheres = "id<>{$id} and level={$level} and coverMemberId={$coverMemberId} and recordId={$recordId}";
			$upRecordId = ['isShow'=>2]; #其他同级或者其他为不可见
			$this->approvalModel->update($recordWheres, $upRecordId);
		}
		$upApprovalData = ['updateTime'=>time(), 'isShow'=>1, 'adopt'=>$adopt, 'info'=>$info]; #状态为可见 更新审批时间 审核意见
		$upApprovalRet = $this->approvalModel->update($upApprovalWhere, $upApprovalData);
		
		#修改第二级主管的可见状态 条件是必须是通过条件
		if($maxLevel==2 && $status==2){
			$whereLevel = intval($level)+1;
			$levelWhere = "coverMemberId={$coverMemberId} and type={$type} and recordId={$recordId} and level={$whereLevel}";
			$levelData = ['isShow'=>1];
			$this->approvalModel->update($levelWhere, $levelData);
		}
		
		#修改各个表的属性
		switch($type){
			#请假
			case 1:
				#拒绝
				if($status==1){
					#只要一级主管拒绝直接该申请不通过 不再上报上级
					$recordWhere = "id={$recordId}";
					$recordData = ['approvalUserId'=>$memberId, 'status'=>3, 'reason'=>$info,'urgeTime'=>0];
					$ret = $this->leaveModel->update($recordWhere, $recordData); 
					
					if($ret){
						
						#被审批人
						$this->insertMessage(['type'=>3,'recordId'=>$recordId,'approvalId'=>$id,'userId'=>$coverMemberId,'msgInfo'=>'我申请的','createTime'=>time()]);
						#审批人
						$this->insertMessage(['type'=>2,'recordId'=>$recordId,'approvalId'=>$id,'userId'=>$memberId,'msgInfo'=>'我审批的','createTime'=>time()]);
					}
				}
				#通过
				if($status==2){
					#最后一级通过则全通过
					if($maxLevel==1){
						$recordWhere = "id={$recordId}";
						$recordData = ['approvalUserId'=>$memberId, 'status'=>2, 'reason'=>$info,'urgeTime'=>0];
						$ret = $this->leaveModel->update($recordWhere, $recordData);
						if($ret){
							#核心操作 修改考勤表记录
							$this->leaveUpdate($recordId, $coverMemberId);
							#审批人
							$this->insertMessage(['type'=>2,'recordId'=>$recordId,'approvalId'=>$id,'userId'=>$memberId,'msgInfo'=>'我审批的','createTime'=>time()]);
							#被审批人
							$this->insertMessage(['type'=>3,'recordId'=>$recordId,'approvalId'=>$id,'userId'=>$coverMemberId,'msgInfo'=>'我申请的','createTime'=>time()]);
						}
					}
					
					#其他一级通过则不通过
					if($maxLevel==2){
						$recordWhere = "id={$recordId}";
						$recordData = ['approvalUserId'=>$memberId, 'reason'=>$info,'urgeTime'=>0];
						$ret = $this->leaveModel->update($recordWhere, $recordData);
						if($ret){
							#审批人
							$this->insertMessage(['type'=>2,'recordId'=>$recordId,'approvalId'=>$id,'userId'=>$memberId,'msgInfo'=>'我审批的','createTime'=>time()]);
							#被审批人
							$this->insertMessage(['type'=>3,'recordId'=>$recordId,'approvalId'=>$id,'userId'=>$coverMemberId,'msgInfo'=>'我申请的','createTime'=>time()]);
						}
					}
				}
				
			break;
			
			#外出
			case 2:
				#拒绝
				if($status==1){ 
					#只要一级主管拒绝直接该申请不通过 不再上报上级
					$recordWhere = "id={$recordId}";
					$recordData = ['proMemberId'=>$memberId, 'status'=>3, 'statusInfo'=>$info,'updateTime'=>time(),'urgeTime'=>0];
					$ret = $this->outGoModel->update($recordWhere, $recordData);
					if($ret){
						#审批人
						$this->insertMessage(['type'=>2,'recordId'=>$recordId,'approvalId'=>$id,'userId'=>$memberId,'msgInfo'=>'我审批的','createTime'=>time()]);
						#被审批人
						$this->insertMessage(['type'=>3,'recordId'=>$recordId,'approvalId'=>$id,'userId'=>$coverMemberId,'msgInfo'=>'我申请的','createTime'=>time()]);
					}
					
				}
				#通过
				if($status==2){
					#最后一级通过则全通过
					if($maxLevel==1){
						$recordWhere = "id={$recordId}";
						$recordData = ['proMemberId'=>$memberId, 'status'=>2, 'statusInfo'=>$info,'updateTime'=>time(),'urgeTime'=>0];
						$ret = $this->outGoModel->update($recordWhere, $recordData);
						if($ret){
							#核心操作 ，修改考勤表记录
							$this->outgoUpdate($recordId, $coverMemberId);
							#审批人
							$this->insertMessage(['type'=>2,'recordId'=>$recordId,'approvalId'=>$id,'userId'=>$memberId,'msgInfo'=>'我审批的','createTime'=>time()]);
							#被审批人
							$this->insertMessage(['type'=>3,'recordId'=>$recordId,'approvalId'=>$id,'userId'=>$coverMemberId,'msgInfo'=>'我申请的','createTime'=>time()]);
						}
					}
					
					#其他一级通过则不通过
					if($maxLevel==2){
						$recordWhere = "id={$recordId}";
						$recordData = ['proMemberId'=>$memberId, 'statusInfo'=>$info,'updateTime'=>time(),'urgeTime'=>0];
						$ret = $this->outGoModel->update($recordWhere, $recordData);
						if($ret){
							#审批人
							$this->insertMessage(['type'=>2,'recordId'=>$recordId,'approvalId'=>$id,'userId'=>$memberId,'msgInfo'=>'我审批的','createTime'=>time()]);
							#被审批人
							$this->insertMessage(['type'=>3,'recordId'=>$recordId,'approvalId'=>$id,'userId'=>$coverMemberId,'msgInfo'=>'我申请的','createTime'=>time()]);
						}
					}
				}
				
			break;
			
			#补卡
			case 3:
				#拒绝
				if($status==1){
					#只要一级主管拒绝直接该申请不通过 不再上报上级
					$recordWhere = "id={$recordId}";
					$recordData = ['approvalUserId'=>$memberId, 'status'=>3, 'remark'=>$info,'urgeTime'=>0];
					$ret = $this->cardModel->update($recordWhere, $recordData);
					if($ret){
						#审批人
						$this->insertMessage(['type'=>2,'recordId'=>$recordId,'approvalId'=>$id,'userId'=>$memberId,'msgInfo'=>'我审批的','createTime'=>time()]);
						#被审批人
						$this->insertMessage(['type'=>3,'recordId'=>$recordId,'approvalId'=>$id,'userId'=>$coverMemberId,'msgInfo'=>'我申请的','createTime'=>time()]);
					}
					
				}
				#通过
				if($status==2){
					#最后一级通过则全通过
					if($maxLevel==1){
						$recordWhere = "id={$recordId}";
						$recordData = ['approvalUserId'=>$memberId, 'status'=>2, 'remark'=>$info,'urgeTime'=>0];
						$ret = $this->cardModel->update($recordWhere, $recordData);
						if($ret){
							#核心操作 ，修改考勤表记录
							$this->repaiRcardUpdate($recordId, $coverMemberId);
							#审批人
							$this->insertMessage(['type'=>2,'recordId'=>$recordId,'approvalId'=>$id,'userId'=>$memberId,'msgInfo'=>'我审批的','createTime'=>time()]);
							#被审批人
							$this->insertMessage(['type'=>3,'recordId'=>$recordId,'approvalId'=>$id,'userId'=>$coverMemberId,'msgInfo'=>'我申请的','createTime'=>time()]);
						}
					}
					
					#其他一级通过则不通过
					if($maxLevel==2){
						$recordWhere = "id={$recordId}";
						$recordData = ['approvalUserId'=>$memberId, 'remark'=>$info,'urgeTime'=>0];
						$ret = $this->cardModel->update($recordWhere, $recordData);
						if($ret){
							#审批人
							$this->insertMessage(['type'=>2,'recordId'=>$recordId,'approvalId'=>$id,'userId'=>$memberId,'msgInfo'=>'我审批的','createTime'=>time()]);
							#被审批人
							$this->insertMessage(['type'=>3,'recordId'=>$recordId,'approvalId'=>$id,'userId'=>$coverMemberId,'msgInfo'=>'我申请的','createTime'=>time()]);
						}
					}
				}
			break;
			
			default:
			
			return false;
		} 
		#改变则修改成功
		if($ret){
			return true;
		}
		return false;
	 }
	 
	 //插入消息中心记录 此为公共方法
	 public function insertMessage($data = []){
		 if(empty($data)){return false;}
		 
		 $ret = $this->msgModel->insert($data);
		 if($ret){
			return true;
		 }
		 return false;
	 }
	 
	 //外出申请通过后续处理 申请的记录id 被审批人userId status ='审核状态：1：审批中 2：通过 3：不通过 4：用户撤回
	 private function outgoUpdate($recordId, $userId){
		#查出申请记录
		$outgoWhere = "id={$recordId} and memberId={$userId} and status=2";
		$outgoFiled = "id,memberId,startTime,endTime";
		$outgoInfo = $this->outGoModel->selectOne($outgoWhere, $outgoFiled);
		
		#找该用户考勤组id
		$memberWhere = "memberId={$userId}"; #  and status=0 #目前做的物理删除该字段暂未用到 type1:参与考勤人员 2：无需参与考勤人员 and type=1
		$memberGroup = $this->groupUserModel->selectOne($memberWhere, '*');
		$agId = $memberGroup['agId'] ? $memberGroup['agId'] : 0; #考勤组id
		#请假的开始时间和结束时间
		$startTime = $outgoInfo['startTime'] ? $outgoInfo['startTime']:"";
		$endTime = $outgoInfo['endTime'] ? $outgoInfo['endTime']:"";
		#考勤规则
		$agRule = $this->groupModel->selectOne("id={$agId}", '*');
		#根据考勤规则来查询需要添加的考勤记录
		//TODO
		
		
		
		#根据时间段直接修改考勤记录表的数据
		$upWhere = "memberId={$userId} and agId={$agId} and isGo=1 and (UNIX_TIMESTAMP(concat(sureDate,' ',sureTime)) BETWEEN {$startTime} AND {$endTime})";
		$upData = ['isGo'=>2];
		$ret = $this->attRecordModel->update($upWhere, $upData);
		if($ret){
			return true;
		}
		
		return false;
	 }
	 
	 //请假申请通过后续处理
	 private function leaveUpdate($recordId, $userId){
		#查出申请记录
		$leaveWhere = "id={$recordId} and memberId={$userId} and status=2";
		$leaveFiled = "id,memberId,startTime,endTime";
		$leaveInfo = $this->leaveModel->selectOne($leaveWhere, $leaveFiled);
		
		#找该用户考勤组id
		$memberWhere = "memberId={$userId}"; #  and status=0 #目前做的物理删除该字段暂未用到 type1:参与考勤人员 2：无需参与考勤人员 and type=1
		$memberGroup = $this->groupUserModel->selectOne($memberWhere, '*');
		$agId = $memberGroup['agId'] ? $memberGroup['agId'] : 0; #考勤组id
		#请假的开始时间和结束时间
		$startTime = $leaveInfo['startTime']?$leaveInfo['startTime']:"0";
		$endTime = $leaveInfo['endTime'] ? $leaveInfo['endTime']:"0";
		#考勤规则
		$agRule = $this->groupModel->selectOne("id={$agId}", '*');
		#根据考勤规则来查询需要添加的考勤记录
		//TODO
		
		
		
		#根据时间段直接修改考勤记录表的数据
		$upWhere = "memberId={$userId} and agId={$agId} and (UNIX_TIMESTAMP(concat(sureDate,' ',sureTime)) BETWEEN {$startTime} AND {$endTime})";
		$upDate = ['leaveIn'=>2, 'leaveInId'=>$recordId,'absenteeism'=>0, 'abnormal'=>0];
		$ret = $this->attRecordModel->update($upWhere, $upDate);
		if($ret){
			#先查询这个打卡是否是正常打卡 只要请假标签包含在时间内李巧说的按照班次进行查询 ！！！
			/*$upWhere = "memberId={$userId} and agId={$agId} and (UNIX_TIMESTAMP(concat(sureDate,' ',sureTime)) BETWEEN {$startTime} AND {$endTime}) and no=1";
			$upFiled = "id,memberId,agId,clockinTime,no";
			$recordList = $this->attRecordModel->select($upWhere, $upFiled)->items;
			if(!empty($recordList)){
				$newInStr = [];
				foreach($recordList as $v){
					$newInStr[] = $v['id'];
				}
			}
			#修改打开时间不在这个区间的，然后改回正常的
			$inStr = implode(","$newInStr);
			$upWhere = "memberId={$userId} and agId={$agId} and (UNIX_TIMESTAMP(concat(sureDate,' ',sureTime)) BETWEEN {$startTime} AND {$endTime}) and no=1";*/
			
			return true;
		}
		
		return false;
	 }
	 
	 //补卡申请通过后续处理
	 private function repaiRcardUpdate($recordId, $userId){
		
		$cardWhere = "id={$recordId}";
		$cardInfo = $this->cardModel->selectOne($cardWhere, 'id,cardId,time');
		$cardId = $cardInfo['cardId'] ? $cardInfo['cardId']:0;
		
		$upWhere = "id={$cardId}";
		$upData = ['no'=>3, 'noId'=>$recordId,'clockinTime'=>$cardInfo['time']];
		
		$ret = $this->attRecordModel->update($upWhere, $upData);
		
		if($ret){
			return true;
		}
		
		return false;
	 }
	 
	 // 计算时间
	 private function getFormatDate($time){
		$t=time()-$time;
		$f=array(
			'31536000'=>'年',
			'2592000'=>'个月',
			'604800'=>'星期',
			'86400'=>'天',
			'3600'=>'小时',
			'60'=>'分钟',
			'1'=>'秒'
		);
		foreach ($f as $k=>$v) {
			if (0 !=$c=floor($t/(int)$k)) {
				return '等待'.$c.$v;
			}
		}
	}
	
	
	
	

}